package com.education.ai.dao.impl;

import com.education.ai.dao.StudentMistakeCollectionDao;
import com.education.ai.entity.StudentMistakeCollection;
import com.education.ai.util.JdbcUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 学生错题集DAO实现类
 */
@Repository
public class StudentMistakeCollectionDaoImpl implements StudentMistakeCollectionDao {

    @Autowired
    private JdbcUtil jdbcUtil;

    @Override
    public StudentMistakeCollection save(StudentMistakeCollection mistake) {
        if (mistake.getId() == null) {
            // 插入操作
            String sql = "INSERT INTO student_mistake_collection (student_id, exercise_id, subject, " +
                    "topic, question, correct_answer, mistake_count, last_mistake_time, created_at) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

            // 设置创建时间
            LocalDateTime now = LocalDateTime.now();
            if (mistake.getCreateTime() == null) {
                mistake.setCreateTime(now);
            }
            if (mistake.getLastMistakeTime() == null) {
                mistake.setLastMistakeTime(now);
            }
            
            // 如果knowledgePoint为空，提供一个默认值
            String topic = mistake.getKnowledgePoint();
            if (topic == null || topic.isEmpty()) {
                topic = "综合";
            }
            
            long id = jdbcUtil.executeInsert(sql, 
                    mistake.getStudentId(),
                    mistake.getExerciseId(),
                    mistake.getSubject(),
                    topic,
                    mistake.getContent(),
                    mistake.getCorrectAnswer(),
                    mistake.getMistakeCount(),
                    mistake.getLastMistakeTime(),
                    mistake.getCreateTime());
            
            mistake.setId(id);
            return mistake;
        } else {
            // 更新操作
            String sql = "UPDATE student_mistake_collection SET " +
                    "student_id = ?, exercise_id = ?, subject = ?, " +
                    "topic = ?, question = ?, correct_answer = ?, " +
                    "mistake_count = ?, last_mistake_time = ? " +
                    "WHERE id = ?";
            
            // 如果knowledgePoint为空，提供一个默认值
            String topic = mistake.getKnowledgePoint();
            if (topic == null || topic.isEmpty()) {
                topic = "综合";
            }
            
            jdbcUtil.executeUpdate(sql,
                    mistake.getStudentId(),
                    mistake.getExerciseId(),
                    mistake.getSubject(),
                    topic,
                    mistake.getContent(),
                    mistake.getCorrectAnswer(),
                    mistake.getMistakeCount(),
                    mistake.getLastMistakeTime(),
                    mistake.getId());
            
            return mistake;
        }
    }

    @Override
    public StudentMistakeCollection findById(Long id) {
        String sql = "SELECT * FROM student_mistake_collection WHERE id = ?";
        List<Map<String, Object>> results = jdbcUtil.executeQuery(sql, id);
        
        if (!results.isEmpty()) {
            return mapRowToMistake(results.get(0));
        }
        
        return null;
    }

    @Override
    public List<StudentMistakeCollection> findByStudentId(String studentId) {
        String sql = "SELECT m.*, d.student_answer AS detail_student_answer, d.explanation AS detail_explanation " +
                    "FROM student_mistake_collection m " +
                    "LEFT JOIN student_practice_details d " +
                    "ON m.exercise_id = d.exercise_id " +
                    "WHERE m.student_id = ? " +
                    "ORDER BY m.last_mistake_time DESC";
        List<Map<String, Object>> results = jdbcUtil.executeQuery(sql, studentId);
        
        return mapResultsToMistakes(results);
    }

    @Override
    public List<StudentMistakeCollection> findByStudentIdAndSubject(String studentId, String subject) {
        String sql = "SELECT m.*, d.student_answer AS detail_student_answer, d.explanation AS detail_explanation " +
                    "FROM student_mistake_collection m " +
                    "LEFT JOIN student_practice_details d " +
                    "ON m.exercise_id = d.exercise_id " +
                    "WHERE m.student_id = ? AND m.subject = ? " +
                    "ORDER BY m.last_mistake_time DESC";
        List<Map<String, Object>> results = jdbcUtil.executeQuery(sql, studentId, subject);
        
        return mapResultsToMistakes(results);
    }

    @Override
    public List<StudentMistakeCollection> findByStudentIdAndExerciseId(String studentId, Long exerciseId) {
        String sql = "SELECT * FROM student_mistake_collection WHERE student_id = ? AND exercise_id = ?";
        List<Map<String, Object>> results = jdbcUtil.executeQuery(sql, studentId, exerciseId);
        
        return mapResultsToMistakes(results);
    }

    @Override
    public void deleteById(Long id) {
        String sql = "DELETE FROM student_mistake_collection WHERE id = ?";
        jdbcUtil.executeUpdate(sql, id);
    }

    @Override
    public List<StudentMistakeCollection> saveAll(List<StudentMistakeCollection> mistakes) {
        List<StudentMistakeCollection> savedMistakes = new ArrayList<>();
        for (StudentMistakeCollection mistake : mistakes) {
            savedMistakes.add(save(mistake));
        }
        return savedMistakes;
    }
    
    /**
     * 将查询结果映射为错题集对象列表
     */
    private List<StudentMistakeCollection> mapResultsToMistakes(List<Map<String, Object>> results) {
        List<StudentMistakeCollection> mistakes = new ArrayList<>();
        for (Map<String, Object> row : results) {
            mistakes.add(mapRowToMistake(row));
        }
        return mistakes;
    }
    
    /**
     * 将单行结果映射为错题集对象
     */
    private StudentMistakeCollection mapRowToMistake(Map<String, Object> row) {
        StudentMistakeCollection mistake = new StudentMistakeCollection();
        
        mistake.setId(((Number) row.get("id")).longValue());
        mistake.setStudentId((String) row.get("student_id"));
        
        Object exerciseIdObj = row.get("exercise_id");
        if (exerciseIdObj != null) {
            mistake.setExerciseId(((Number) exerciseIdObj).longValue());
        }
        
        mistake.setSubject((String) row.get("subject"));
        mistake.setKnowledgePoint((String) row.get("topic"));
        mistake.setContent((String) row.get("question"));
        
        // 优先使用student_practice_details表中的学生答案
        String studentAnswer = (String) row.get("detail_student_answer");
        if (studentAnswer == null) {
            studentAnswer = (String) row.get("student_answer");
        }
        mistake.setStudentAnswer(studentAnswer);
        
        mistake.setCorrectAnswer((String) row.get("correct_answer"));
        
        // 优先使用student_practice_details表中的解析
        String analysis = (String) row.get("detail_explanation");
        if (analysis == null) {
            analysis = (String) row.get("analysis");
        }
        mistake.setAnalysis(analysis);
        
        Object mistakeCountObj = row.get("mistake_count");
        if (mistakeCountObj != null) {
            mistake.setMistakeCount(((Number) mistakeCountObj).intValue());
        }
        
        if (row.get("last_mistake_time") != null) {
            mistake.setLastMistakeTime(jdbcUtil.convertToLocalDateTime(row.get("last_mistake_time")));
        }
        
        if (row.get("created_at") != null) {
            mistake.setCreateTime(jdbcUtil.convertToLocalDateTime(row.get("created_at")));
        }
        
        return mistake;
    }
} 